package com.mingsoft.cms.action.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mingsoft.base.filter.DateValueFilter;
import com.mingsoft.base.filter.DoubleValueFilter;
import com.mingsoft.basic.action.BaseAction;
import com.mingsoft.basic.biz.IColumnBiz;
import com.mingsoft.basic.entity.CategoryEntity;
import com.mingsoft.basic.entity.ColumnEntity;
import com.mingsoft.cms.biz.IBasePropertyBiz;
import com.mingsoft.cms.biz.ICompanyBiz;
import com.mingsoft.cms.biz.IInsuranceBiz;
import com.mingsoft.cms.biz.IPropertyValueBiz;
import com.mingsoft.cms.constant.ModelCode;
import com.mingsoft.cms.entity.BasePropertyEntity;
import com.mingsoft.cms.entity.InsuranceEntity;
import com.mingsoft.cms.entity.InsurancePriceEntity;
import com.mingsoft.cms.entity.InsurancePropertyEntity;
import com.mingsoft.cms.entity.PropertyValueEntity;
import com.mingsoft.cms.entity.InsuranceEntity;
import com.mingsoft.util.JsonUtil;
import com.mingsoft.util.StringUtil;

import net.mingsoft.base.util.JSONObject;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.util.BasicUtil;

@Controller("insurance")
@RequestMapping("/${managerPath}/goods/insurance")
public class InsuranceAction extends BaseAction{
    /**
     * 注入博客文章业务层
     */    
	  @Autowired
    private IInsuranceBiz insuranceBiz;
    
    @Autowired
    private ICompanyBiz companyBiz;
    
    /**
     * 注入博客文章业务层
     */    
    @Autowired
    private IBasePropertyBiz basePropertyBiz;
    
    @Autowired
    private IPropertyValueBiz propertyValueBiz;
	/**
	 * 栏目管理业务处理层
	 */
	@Autowired
	private IColumnBiz columnBiz;
    /**
     * 返回主界面index
     */
    @RequestMapping("/index")
    public String index(HttpServletResponse response,HttpServletRequest request){
    	// 获取站点id
    	List<ColumnEntity> list = getChildList(149);
    	request.setAttribute("listColumn", JSONArray.toJSONString(list));
    	return view ("/goods/insurance_index");
    }
    /**
     * 返回主界面index
     */
    @RequestMapping("/main")
    public String main(HttpServletResponse response,HttpServletRequest request,ModelMap model){
    	
    	String insType = request.getParameter("insType");
    	String isParent = request.getParameter("isParent");
    	model.addAttribute("insType",insType);
    	model.addAttribute("isParent",isParent);
    	
    	return view ("/goods/insurance_main");
    }
  
    /**
     * 保险产品列表
     * @param insurance
     * @param response
     * @param request
     * @param model
     */
    @RequestMapping("/list")
    @ResponseBody
    public void list(@ModelAttribute InsuranceEntity insurance,HttpServletResponse response, HttpServletRequest request,ModelMap model) {
        
        String isParent = request.getParameter("isParent");
        //查询当前ID下的所有文章
        Integer insTypes = insurance.getInsType();
        int[] _columnIds = columnBiz.queryChildrenCategoryIds(insTypes, 1,0);
       
        
        List<Integer> instype = new ArrayList<Integer>();
        for (int i : _columnIds) {
        	instype.add(i);
		}
 
        if(_columnIds.length > 0 ){
        	insurance.setInsTypes(_columnIds);
        	insurance.setInsType(null);
        }
        
        BasicUtil.startPage();
        List<InsuranceEntity> basePropertyList = insuranceBiz.query(insurance);
//        List<InsuranceEntity> basePropertyList = insuranceBiz.query(1, 0, null, null, null, true, insurance);
        this.outJson(response, net.mingsoft.base.util.JSONArray.toJSONString(new EUListBean(basePropertyList,(int)BasicUtil.endPage(basePropertyList).getTotal()),new DoubleValueFilter(),new DateValueFilter()));
    }

    /**
     * 返回编辑界面baseProperty_form
     */
    @RequestMapping("/form")
    public String form(@ModelAttribute InsuranceEntity insurance,HttpServletResponse response,HttpServletRequest request,ModelMap model){
    	
    	if(insurance.getInsId() != null){
        	InsuranceEntity InsuranceEntity = (InsuranceEntity) insuranceBiz.getEntity(insurance.getInsId());            
            model.addAttribute("insurance",InsuranceEntity);
            model.addAttribute("insId",InsuranceEntity.getInsId());
            model.addAttribute("insType",InsuranceEntity.getInsType());
            
        }else{
        	model.addAttribute("insurance",new InsuranceEntity());
            model.addAttribute("insType",insurance.getInsType());
        }
        
        List companyList = companyBiz.queryAll();
        model.addAttribute("companyList",companyList);
        
        List<ColumnEntity> columnList = getChildList(149);
        model.addAttribute("columnList", JSONArray.toJSONString(columnList));
        //属性值
        List<BasePropertyEntity> bpList = basePropertyBiz.queryAll();
        List<Map<String,Object>> proList = new ArrayList<Map<String,Object>>();
        for (BasePropertyEntity bp : bpList) {
        	int bpId = bp.getBpId();
        	
        	List<PropertyValueEntity> pvList = propertyValueBiz.queryByBasePropertyId(bpId);
        	Set<Integer> selectList = new HashSet<Integer>();
        	//找到已选择
        	if(insurance.getInsId() != null){
	        	//已选属性
        		String selectSql =" select bpv_id from t_fs_insurance_property"
	        			+ "  where ins_id = " + insurance.getInsId() + " and bp_id =" + bpId;
	        	List<Map<String,Object>> selList = (List<Map<String, Object>>) propertyValueBiz.excuteSql(selectSql);
	        	for (Map<String, Object> map : selList) {
					Integer bpvId = (Integer)map.get("bpv_id");
					selectList.add(bpvId);
				}
	        	
	        	//已先价格
	        	List<Map<String,Object>> priceChoseList = new ArrayList<Map<String,Object>>();
	        	String priceSql = " select ins_property,price from  t_fs_insurance_price where ins_id = "  + insurance.getInsId();
	        	List<Map<String,Object>> priceList = (List<Map<String, Object>>) propertyValueBiz.excuteSql(priceSql);
	        	// oldTableData:[{"price":"200","list":[{"id":1001,"name":"10万以下","check":true,"type":"coverage"},{"id":2002,"name":"二年","type":"period"}]},{"price":"100","list":[{"id":1002,"name":"20万","type":"coverage"},{"id":2002,"name":"二年","type":"period"}]}]
	        	String choseList = "[";
	        	for (Map<String, Object> map : priceList) {
					Map<String,Object> priceMap = new HashMap<String,Object>();
					choseList += "{\"price\":"+ map.get("price") + ",\"list\":"
							  + map.get("ins_property") + "},";
				}
	        	choseList += "]";
	        	model.addAttribute("priceList", choseList);
        	}
        	
        	
        	List<Map<String,Object>> pvMList = new ArrayList<Map<String,Object>>();
        	for (PropertyValueEntity pv : pvList) {
				Map<String,Object> pvMap = new HashMap<String,Object>();
				pvMap.put("id", pv.getPvId());
				pvMap.put("name", pv.getPropertyValue());
				pvMList.add(pvMap);
			}
        	
        	
        	
        	Map bpMap = new HashMap<String,Object>();
        	bpMap.put("label", bp.getPropertyName());
        	bpMap.put("type", "bp_" + bpId);
        	bpMap.put("selected", selectList);
        	bpMap.put("list", pvMList);
        	proList.add(bpMap);
		}
        model.addAttribute("proList", JSONArray.toJSONString(proList));
        
        return view ("/goods/insurance_from");
    }


    /**
     * 获取保险信息
     * @param insurance
     * @param response
     * @param request
     * @param model
     */
    @RequestMapping("/get")
    @ResponseBody
    public void get(@ModelAttribute InsuranceEntity insurance,HttpServletResponse response, HttpServletRequest request,ModelMap model){
        if( 0 == insurance.getInsId()  ) {
            this.outJson(response, null, false, getResString("err.error", this.getResString("insurance.companyId")));
            return;
        }
        InsuranceEntity _insurance = (InsuranceEntity)insuranceBiz.getEntity(insurance);
        this.outJson(response, _insurance);
    }


    /**
     * 保存保险信息
     * @param insurance
     * @param response
     * @param request
     */
    @PostMapping("/save")
    @ResponseBody
    public void save(@ModelAttribute InsuranceEntity insurance, HttpServletResponse response, HttpServletRequest request) {
        //验证文章内容的值是否合法            
        if(StringUtil.isBlank(insurance.getTitle())){
            this.outJson(response, null,false,getResString("err.empty", "保险名称不能为空"));
            return;            
        }
        
        insurance.setDel(0);
        insurance.setCreateDate(new Date());
        insuranceBiz.saveEntity(insurance);//如果是普通模版 直接调用saveEntity(company)
        
        String propertyJson =  request.getParameter("propertyId");
        if(StringUtils.isNotBlank(propertyJson)){
        	saveProperty(propertyJson,insurance.getInsId(),"save");
        }
        
        this.outJson(response, JSONObject.toJSONString(insurance));
    }

    /**
     * 更新保险信息
     * @param insurances
     * @param response
     * @param request
     */
    @RequestMapping("/delete")
    @RequiresPermissions("insurance:delete")
    @ResponseBody
    public void delete(@RequestBody List<InsuranceEntity> insurances,HttpServletResponse response, HttpServletRequest request) {
        int[] ids = new int[insurances.size()];
        for(int i = 0;i<insurances.size();i++){
            int insId = insurances.get(i).getInsId();
          //清空原属性
			String delPrice =" delete from t_fs_insurance_price where ins_id = " + insId;
			String delPro =" delete from t_fs_insurance_property where ins_id = " + insId;
			insuranceBiz.excuteSql(delPrice);
			insuranceBiz.excuteSql(delPro);
			
        	ids[i] = insId;
        }
        insuranceBiz.deleteBasic(ids);    
        this.outJson(response, true);
    }
    
    /**
     * 更新上下架信息
     * @param insurances
     * @param response
     * @param request
     */
    @RequestMapping("/updateStatus")
    @ResponseBody
    public void updateStatus(@RequestBody List<InsuranceEntity> insurances,HttpServletResponse response, HttpServletRequest request) {
    	int[] ids = new int[insurances.size()];
    	for(int i = 0;i<insurances.size();i++){
    		int insId = insurances.get(i).getInsId();
    		ids[i] = insId;
    	}
    	String status = request.getParameter("status");
    	if(StringUtils.isNotBlank(status)){
    		insuranceBiz.updateStatus(ids,Integer.valueOf(status));  
    	}
    	  
    	this.outJson(response, true);
    }

   
    @PostMapping("/update")
    @ResponseBody     
    public void update(@ModelAttribute InsuranceEntity insurances, HttpServletResponse response,
            HttpServletRequest request) {
        //验证文章内容的值是否合法            
        if(StringUtil.isBlank(insurances.getTitle())){
            this.outJson(response, null,false,getResString("err.empty", "保险名称为空"));
            return;            
        }
        insurances.setUpdateDate(new Date());
        insuranceBiz.updateEntity(insurances);//如果是普通模版 直接调用updateEntity(baseProperty)
        String propertyJson =  request.getParameter("propertyId");
        if(StringUtils.isNotBlank(propertyJson)){
        	saveProperty(propertyJson,insurances.getInsId(),"update");
        }
        
        this.outJson(response, JSONObject.toJSONString(insurances));
    }
    
	public void saveProperty(String propertyJson, Integer insId,String action) {
		
		if("update".equals(action)){
			//清空原属性
			String delPrice =" delete from t_fs_insurance_price where ins_id = " + insId;
			String delPro =" delete from t_fs_insurance_property where ins_id = " + insId;
			insuranceBiz.excuteSql(delPrice);
			insuranceBiz.excuteSql(delPro);
		}
		
		List<Map> priceList = JsonUtil.queryJsonToList(propertyJson, Map.class);
		for (Map map : priceList) {
			String price = (String) map.get("price");
			JSONArray list = (JSONArray) map.get("list");
			// 保存价格JSON
			InsurancePriceEntity ipe = new InsurancePriceEntity();
			ipe.setInsId(insId);
			ipe.setInsProperty(list.toString());
			ipe.setPrice(new BigDecimal(price));
			insuranceBiz.savePrice(ipe);
			// 属性列表
			List<Object> proList = list;
			for (Object proMap : proList) {
				Map toMap = (Map) proMap;
				Integer pid = (Integer) toMap.get("id");
				String type = (String) toMap.get("type");
				String[] types = type.split("_");
				// 写入商品价格属性
				InsurancePropertyEntity iproe = new InsurancePropertyEntity();
				iproe.setBpId(Integer.valueOf(types[1]));
				iproe.setBpvId(pid);
				iproe.setInsId(insId);
				insuranceBiz.saveProperty(iproe);

			}
		}

	}
    
	public List<ColumnEntity> getChildList(int parentId) {
		List<ColumnEntity> list = new ArrayList<ColumnEntity>();

		List<ColumnEntity> tempList = columnBiz.queryChildListByColumnId(149, null);
		list.addAll(tempList);
		for (ColumnEntity ce : tempList) {

			List<ColumnEntity> twoCategoryList = columnBiz.queryChildListByColumnId(ce.getCategoryId(), null);
			list.addAll(twoCategoryList);
			for (ColumnEntity ce2 : twoCategoryList) {

				List<ColumnEntity> threeCategoryList = columnBiz.queryChildListByColumnId(ce2.getCategoryId(), null);
				list.addAll(threeCategoryList);

			}

		}

		return list;
	}

}